﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text.RegularExpressions;

namespace Leet
{
    class Program
    {
        public static int PID = 684;

        static void Main(string[] args)
        {
            //反射找到所有的Corde类
            var dic = GetAllProgramTypes();
            int curID = -1;
            //先从输入参数里面找题号
            foreach (var arg in args)
            {
                if (int.TryParse(arg, out curID))
                {
                    break;
                }
            }

            //如果没有 就用PID;
            if (!dic.ContainsKey(curID))
            {
                curID = PID;
            }

            if (!dic.ContainsKey(curID))
            {
                throw new Exception($"There is No Solution for Program:{curID}");
            }

            dic[curID].Invoke(null, null);
        }

        //  

        static Dictionary<int, MethodInfo> GetAllProgramTypes()
        {
            var dic = new Dictionary<int, MethodInfo>();
            var assembly = Assembly.GetExecutingAssembly();
            var types = assembly.GetTypes();
            Regex rg = new Regex(@"^P[0-9]+$");
            Regex numberRg = new Regex(@"[0-9]+$");

            foreach (var type in types)
            {
                var name = type.Name;
                if (!rg.IsMatch(name))
                    continue;
                var method = type.GetMethod("Run");
                if (method == null)
                    continue;
                var collection = numberRg.Matches(name);
                foreach (Match match in collection)
                {
                    int number = -1;
                    if (int.TryParse(match.Value, out number))
                    {
                        if (dic.ContainsKey(number))
                        {
                            throw new Exception("There is multi NO:" + number + " in the project");
                        }
                        dic[number] = method;
                    }
                }
            }
            return dic;
        }
    }
}
